package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.OrderList;
import com.flycent.hqhs.bean.OrderList.OrderItemDTOs;
import com.flycent.hqhs.bean.OrderList.OrderStatus;
import com.flycent.hqhs.bean.OrderList.PaymentStatus;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.HorizontalListView;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.util.ContextUtil;
import com.flycent.hqhs.util.DateTimeUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 *  我的订单
 */
public class OrderManagerActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{
	
	private static final String TAG = "OrderManagerActivity";
	
	public static final String SN = "sn";
	
	@ViewInject(id = R.id.order_radio0 ,click = "butClick") RadioButton radio0;
	@ViewInject(id = R.id.order_radio1 ,click = "butClick") RadioButton radio1;
	@ViewInject(id = R.id.order_radio2 ,click = "butClick") RadioButton radio2;
	@ViewInject(id = R.id.order_radio3 ,click = "butClick") RadioButton radio3;
	@ViewInject(id = R.id.order_manager_loading_text ) TextView mLoadingText;
	@ViewInject(id = R.id.order_empty_relat ) RelativeLayout mEmptyRelat;

	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private int nowPage = 1;
	private OrderManagerAdapter mAdapter;
	private List<OrderList> mOrderLists;
	private String mOrderStatus = "";
	private Handler mHandler = new MyHandler(this);

	//---------------------------------------------------------------------
	
	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_order_manager);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.title_order_manager);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.order_form_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new OrderManagerAdapter(this,R.layout.item_order_manager);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);

		mLoadMoreProxy.refreshing();

		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
				Intent intent = new Intent(OrderManagerActivity.this,OrderDetailActivity.class);
				intent.putExtra(SN, mAdapter.getData().get(position-1).getSn()+"");
				startActivity(intent);
			
			}

		});

	}

	//---------------------------------------------------------------------
	/**
	 * Refesh Order List by pageNumber...
	 * @param pageNum
	 * @param isRefresh
	 */
	private void updateOrderListAsync(final int pageNum,final boolean isRefresh){

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(OrderManagerActivity.this);

					PageEntity<OrderList> mEntity =  client.getOrderList(mOrderStatus,1,20,"","");
					int totlePage = mEntity.getTotalPages();

					mOrderLists = mEntity.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mOrderLists = null;
					}
				} catch (WebException e) {
					
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mOrderLists = null;
					else{
						Log.e(TAG, e.toString());
					}
				}catch (Exception e) {
					App.showShortToast(R.string.unknownerror);
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

	}
	
	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity  = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if(mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					canClick(true);
					if(mOrderLists == null){
						App.showShortToast("没有该类订单信息");
					}

					mAdapter.update(mOrderLists);
					mRefreshListView.setSelection(0);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					canClick(true);
					mAdapter.append(mOrderLists);
					mRefreshListView.onRefreshComplete();
					break;
				default:
					break;
				}
				
			}
		}
	}
	



	public void butClick(View v){
		if( v == radio0){
			canClick(false);
			mOrderStatus = "";
			onRefresh(1);
		}
		if( v == radio1){
			canClick(false);
			mOrderStatus = "unconfirmed";
			onRefresh(1);


		}
		if( v == radio2){
			canClick(false);
			mOrderStatus = "shipped";
			onRefresh(1);

		}
		if( v == radio3){
			canClick(false);
			mOrderStatus = "MEMBER_SIGNED&reviewStatus=false";
			onRefresh(1);

		}
	}



	private void canClick(boolean b){
		radio0.setClickable(b);
		radio1.setClickable(b);
		radio2.setClickable(b);
		radio3.setClickable(b);
		if(b){
			mLoadingText.setVisibility(View.GONE);
		}else{
			mLoadingText.setVisibility(View.VISIBLE);
		}

	}
	public class OrderManagerAdapter extends AbsViewHolderAdapter<OrderList>{
		
		public OrderManagerAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, OrderList itemData) {
			
			LinearLayout mSingerLin = getViewFromHolder(R.id.item_order_single_lin);
			LinearLayout mDoubleLin = getViewFromHolder(R.id.item_order_double_lin);

			TextView mOrderNumberText = getViewFromHolder(R.id.item_order_mag_text2);
			TextView mOrderTimeText = getViewFromHolder(R.id.item_order_manager_time_text);
			TextView mOrderStateText = getViewFromHolder(R.id.item_order_manager_state);
			TextView mOrderMoneyText = getViewFromHolder(R.id.item_order_money);
			final TextView mOrderTackingText = getViewFromHolder(R.id.order_tacking_text);

			mOrderNumberText.setText(itemData.getSn()+"");
			mOrderTimeText.setText(DateTimeUtil.getDateTime(itemData.getCreateDate()));
			//mOrderStateText.setText(OrderUtil.getOrderStatus(itemData.getOrderStatus()));
			mOrderMoneyText.setText("￥"+itemData.getPrice());

			List<OrderItemDTOs> mDtOs = itemData.getOrderItemDTOs();
			List<String> imagePath = new ArrayList<String>(); 
			for (int i = 0; i < mDtOs.size(); i++) {
					imagePath.add(mDtOs.get(i).getItem().getImage());
			}
			if( imagePath.size() == 1){
				mSingerLin.setVisibility(View.VISIBLE);
				mDoubleLin.setVisibility(View.GONE);
				ImageView imge = getViewFromHolder(R.id.item_order_product_img);
				TextView text = getViewFromHolder(R.id.item_order_product_name);
				ImageLoader.getInstance().displayImage(imagePath.get(0), imge);
				text.setText(mDtOs.get(0).getItem().getName());
			}else {
				mSingerLin.setVisibility(View.GONE);
				mDoubleLin.setVisibility(View.VISIBLE);

				OrderHorizonAdapter mOrderHorzinAdapter = new OrderHorizonAdapter(OrderManagerActivity.this, R.layout.item_order_manager_double_image);
				HorizontalListView hoListView = getViewFromHolder(R.id.order_image_list);
				hoListView.setAdapter(mOrderHorzinAdapter);
				mOrderHorzinAdapter.update(imagePath);

			}
			

			OrderStatus orderStatus  = itemData.getOrderStatus();			
			if(OrderStatus.unconfirmed.equals(orderStatus)){
				
				mOrderStateText.setText("待付款");
				mOrderTackingText.setText("去付款");
				mOrderTackingText.setVisibility(View.VISIBLE);

			}else if(OrderStatus.confirmed.equals(orderStatus)){
				
				PaymentStatus paymentStatus = itemData.getPaymentStatus();
				Log.d(TAG, "SN: " + String.valueOf(itemData.getSn()) + " PaymentStatus Status: " + paymentStatus.toString());
				if(paymentStatus.equals(PaymentStatus.partialPayment)){
					
					mOrderStateText.setText("待付款");
					mOrderTackingText.setText("去付款");
					mOrderTackingText.setVisibility(View.VISIBLE);
				}else if(paymentStatus.equals(PaymentStatus.paid)){
					mOrderStateText.setText( "待发货");
					mOrderTackingText.setVisibility(View.GONE);
				}else {
					// other payment status....
				}
				
			}else if (OrderStatus.completed.equals(orderStatus) || OrderStatus.returned.equals(orderStatus) 
					|| OrderStatus.exchanged.equals(orderStatus)) {
				
				mOrderStateText.setText( "已完成");	
				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.VISIBLE);

				
			}else if(OrderStatus.cancelled.equals(orderStatus) ){
				
				mOrderStateText.setText( "已取消");
//				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.INVISIBLE);
				
			}else if(OrderStatus.orderReceived.equals(orderStatus) || OrderStatus.stockVerifying.equals(orderStatus) 
					||OrderStatus.purchasing.equals(orderStatus) || OrderStatus.picking.equals(orderStatus)){
				mOrderStateText.setText( "待发货");
				mOrderTackingText.setVisibility(View.GONE);
				
			}else if (OrderStatus.returning.equals(orderStatus)) {
			
				mOrderStateText.setText( "退货中");
				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.VISIBLE);

			//无须评价
			}else if (OrderStatus.exchanging.equals(orderStatus)) {
				
				mOrderStateText.setText( "换货中" );
				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.VISIBLE);
				//无须评价
			}else if (OrderStatus.toBeConfirmed.equals(orderStatus)) {
				
				mOrderStateText.setText( "待收货");
				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.VISIBLE);

			}else if(OrderStatus.shipped.equals(orderStatus)){
				
				mOrderStateText.setText( "发货中");
				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.VISIBLE);

			}else if(OrderStatus.MEMBER_SIGNED.equals(orderStatus)){
				mOrderStateText.setText( "已完成");
				
//				if( !itemData.isReviewStatus() && !itemData.isSunSingleStatus() ){
//					mOrderTackingText.setText("评价/晒单");	
//				}else if(!itemData.isReviewStatus() && itemData.isSunSingleStatus()){
//					mOrderTackingText.setText("评价");	
//				}else if(itemData.isReviewStatus() && !itemData.isSunSingleStatus()){
//					mOrderTackingText.setText("晒单");	
//				}
				mOrderTackingText.setText("查看物流");
				mOrderTackingText.setVisibility(View.VISIBLE);
			}
					
			
			mOrderTackingText.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					if("去付款".equals(getText(mOrderTackingText))){
						App.showShortToast("去付款");
					}else {
						ContextUtil.startActivity(OrderManagerActivity.this, OrderTrackingActivity.class);
					}

				}
			});
		}
		


	}

	/** 多个商品下横向图片滑动 */
	public static class OrderHorizonAdapter extends AbsViewHolderAdapter<String>{
		public OrderHorizonAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, String itemData) {
			ImageView mImg = getViewFromHolder(R.id.item_order_manager_hon_img);
			ImageLoader.getInstance().displayImage(itemData.toString(), mImg);
		}
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		
	}
	

	@Override
	public void onRefresh(int page) {
		updateOrderListAsync(1, true);
	}


	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateOrderListAsync(nowPage, false);
	} 

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
